import axios from 'axios'
import store from '@/store'
import iView from 'iview';
// import { Spin } from 'iview'
import router from '@/router'
import { setToken, setRefreshToken, getToken, getRefreshToken, setRole, getRole } from '@/libs/util'
const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
    axios.defaults.transformRequest = [function (data) {
      let ret = '';
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
      }
      return ret;
    }]
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {

      this.destroy(url)
      const { data, status } = res

      let oldConfig = res.config;
      if(status == 200 && data.code == 402) {
        this.destroy(url)
        let data = {
          'refreshToken': getRefreshToken()
        }
        return new Promise((resolve,reject)=>{
          this.request({
            url: '/getAccessToken',
            data,
            method: 'post'
          }).then(res => {
            if (res.data.code == 200) {
              setToken(res.data.data.accessToken)
              //继续上次请求
                this.request(oldConfig).then(datas =>{
                  let data = datas.data;
                  resolve( { data, status })
                })
            } else {
              setToken("")
              setRefreshToken("")
              router.push({
                name: 'login'
              })
              return reject("refreshToken expired")
            }
          }).catch(err=> reject())

        })
      }else if(status == 200 && data.code == 1000003){
        iView.Message.error("没有权限，请联系当前管理员")
        return { data, status }
      }else if(data.code == 401){
        setToken("")
        setRefreshToken("")
        router.push({
          name: 'login'
        })
      }
      else{
        return { data, status }
      }


    }, error => {
      this.destroy(url)
      // let errorInfo = error.response
      // if (!errorInfo) {
      //   const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
      //   errorInfo = {
      //     statusText,
      //     status,
      //     request: { responseURL: config.url }
      //   }
      // }
      // addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    let token = getToken();
    if(token) {
      options = Object.assign(options, {
        headers: {'Authorization': getToken()}
      })
    }
    this.interceptors(instance, options.url)
    return instance(options)
  }
  request21 (options) {
    const instance =  axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    let token = getToken();
    if(token) {
      options = Object.assign(options, {
        headers: {'Authorization': getToken()}
      })
    }
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
